package com.promise.jokerdream.work.penguin

import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.database.entity.WlmzGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.utils.AppContext

/**
 * 武林盟主工作
 */
class PenguinWlmzWork(
    private val config: WlmzGameConfigEntity,
    override val uin: String
): BaseWork(uin) {
    
    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }
    
    override val name: String = "武林盟主"
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 查询当前状态
            val queryResult = gameApi.queryWlmz()
            
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // 1. 检查是否需要领奖
                    val awardInfoList = response.getAwardInfoList()
                    if (response.status == 1 && awardInfoList.isNotEmpty()) {
                        val awardInfo = awardInfoList.first()
                        val awardResult = gameApi.getWlmzAward(awardInfo.roundId, awardInfo.sectionId)
                        awardResult.foldWithApiException(
                            onSuccess = { awardResponse ->
                                historyManager.addHistory(name, awardResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                    
                    // 2. 检查是否需要报名（不依赖status）
                    if (response.isSignUp == 1 && response.groundId == 0) {
                        val signupResult = gameApi.signupWlmz(config.getGroundId())
                        signupResult.foldWithApiException(
                            onSuccess = { signupResponse ->
                                historyManager.addHistory(name, signupResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }

                    // 3. 检查是否需要猜排名
                    if (response.guessInfo.groundTips.isNotEmpty() && response.guessInfo.guessConfirm == 1) {
                        var allGuessSuccess = true
                        
                        // 进行8次猜排名（0-7）
                        for (i in 0..7) {
                            val guessResult = gameApi.guessWlmzRanking(i)
                            guessResult.foldWithApiException(
                                onSuccess = { guessResponse ->
                                    historyManager.addHistory(name, guessResponse.getDescription())
                                },
                                onFailure = { code, msg ->
                                    historyManager.addHistory(name, msg, code)
                                    allGuessSuccess = false
                                }
                            )
                        }
                        
                        // 只有所有猜排名都成功才确认猜排名
                        if (allGuessSuccess) {
                            val confirmResult = gameApi.confirmWlmzGuess()
                            confirmResult.foldWithApiException(
                                onSuccess = { confirmResponse ->
                                    historyManager.addHistory(name, confirmResponse.getDescription())
                                },
                                onFailure = { code, msg ->
                                    historyManager.addHistory(name, msg, code)
                                }
                            )
                        }
                    }
                    
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}